﻿using Aspfm.Html;
using Aspfm.Main;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.Serialization.Formatters.Binary;

namespace Aspfm.Tool
{
    public partial class Form1 : Form
    {
        string serverurl = "";
        string htmlpath = "";
        string serverpath = "";
        List<aspfmmodel> allAspfm = null;
        List<aspfmmodel> allAspxHtml = null;

        public Form1()
        {
            InitializeComponent();

            dataGridView1.RowStateChanged += dataGridView1_RowStateChanged;
            dataGridView2.RowStateChanged += dataGridView1_RowStateChanged;

            textBox1.Text = textBox8.Text =textBox9.Text= BaseAshx.CurrentPath();

            //textBox1.Text = textBox8.Text = @"D:\MyWork\MyProject\aspfm\发布版本\设计器";
        }

        void dataGridView1_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
        {
            e.Row.HeaderCell.Value = string.Format("{0}", e.Row.Index + 1);
            e.Row.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox2.Text == "" || textBox3.Text == "")
            {
                MessageBox.Show("服务器地址和输出文件夹都不能为空。");
                return;
            }
            serverurl = textBox2.Text.Trim().Trim('\\').Trim('/');
            htmlpath = textBox3.Text.Trim().Trim('\\').Trim('/');
            serverpath = textBox1.Text.Trim().Trim('\\').Trim('/');

            if (!System.IO.Directory.Exists(htmlpath))
            {
                Directory.CreateDirectory(htmlpath);
            }

            string[] files = Directory.GetFiles(serverpath, "*.aspfm",SearchOption.AllDirectories);
            foreach (string strfile in files)
            {
                CreateHtml(strfile);
            }
            MessageBox.Show("转换完成。文件数：" + files.Length);
            //CreateHtml(@"D:\MyWork\MyProject\aspfm\发布版本\设计器\222.aspfm");
        }
        public void CreateHtml(string strfile)
        {
            if (File.Exists(strfile))
            {
                string strurl = strfile.Replace(serverpath, "").Trim().Trim('\\').Trim('/');

                string urlpath = Path.GetDirectoryName(strurl);
                string htmlname = Path.GetFileNameWithoutExtension(strurl) + ".html";
                string aspxname = Path.GetFileNameWithoutExtension(strurl) + AspfmHtml.pageext;
                
                string cssUrl = "";
                string htmlall = "";

                if (!string.IsNullOrEmpty(urlpath))
                {
                    if (!Directory.Exists(htmlpath + "\\" + urlpath))
                    {
                        Directory.CreateDirectory(htmlpath + "\\" + urlpath);
                    }
                    htmlname = urlpath + "\\" + htmlname;
                    htmlall = PageTool.GetAspx(serverurl + "/" + urlpath+"/" + aspxname);

                    for (; urlpath.Contains('\\'); )
                    {
                        cssUrl += "../";
                        urlpath = urlpath.Substring(urlpath.IndexOf('\\') + 1);
                    }
                    cssUrl += "../";
                }
                else
                {
                    htmlall = PageTool.GetAspx(serverurl + "/" + aspxname);
                }
                htmlall = htmlall.Replace(serverurl + "/", cssUrl).Replace("Aspfm.Data.defaulthtml", "Aspfm.Data.defaulthtml_bak");

                string mainpath = "var _path = \"" + serverurl + "/" + "\";";
                mainpath = mainpath + "Aspfm.Data.defaulthtml='" + strurl.Replace("\\","/") + "';";

                htmlall = htmlall.Replace("var _path = \"" + cssUrl+ "\";", mainpath);


                File.WriteAllText(htmlpath + "\\" + htmlname, htmlall, Encoding.UTF8);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string replacehtml = textBox6.Text.Trim().Trim('\\').Trim('/');
            string oldstr = textBox4.Text.Trim();
            string newstr = textBox5.Text.Trim();
            if (oldstr == "" || newstr == "")
            {
                MessageBox.Show("新旧服务器地址都不能为空。");
                return;
            }
            if (Directory.Exists(replacehtml))
            {
                int ireplace = 0;
                string[] files = Directory.GetFiles(replacehtml, "*.html", SearchOption.AllDirectories);
                foreach (string strfile in files)
                {
                    string strhtml = File.ReadAllText(strfile);
                    if (strhtml.Contains(oldstr))
                    {
                        strhtml = strhtml.Replace(oldstr, newstr);
                        File.WriteAllText(strfile, strhtml, Encoding.UTF8);
                        ireplace++;
                    }
                }
                MessageBox.Show("替换完成。文件数：" + ireplace);
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (allAspfm == null)
            {
                allAspfm = new List<aspfmmodel>();
                serverpath = textBox1.Text.Trim().Trim('\\').Trim('/');
                //string[] files = Directory.GetFiles(serverpath, "*.aspfm", SearchOption.AllDirectories);
                string[] files = ConfigTool.GetFiles(serverpath, "*.aspfm", SearchOption.AllDirectories);
                foreach (string strfile in files)
                {
                    aspfmmodel tempaspfm = new aspfmmodel();
                    tempaspfm.filename = strfile;
                    tempaspfm.aspfmall = AspfmHtml.GetAspfmData(strfile);
                    string aspxfile = Path.GetDirectoryName(strfile) + "\\" + Path.GetFileNameWithoutExtension(strfile) + AspfmHtml.pageext;
                    tempaspfm.html = File.ReadAllText(aspxfile, Encoding.UTF8);
                    if(tempaspfm.aspfmall!=null)
                    {
                        allAspfm.Add(tempaspfm);
                    }
                }
            }
            dataGridView1.Rows.Clear();
            string querystr = textBox7.Text.ToUpper().Trim();
            if (!string.IsNullOrEmpty(querystr))
            {
                foreach (aspfmmodel tempmd in allAspfm)
                {
                    bool ishad = false;
                    string msg = "";
                    foreach (AspfmDataSource aspfmds in tempmd.aspfmall)
                    {
                        if (checkBox1.Checked && aspfmds.strKey.ToUpper().Contains(querystr))
                        {
                            ishad = true;
                            msg += "数据连接关键字、";
                        }
                        if (checkBox3.Checked)
                        {
                            foreach (AspfmUpdateSql up in aspfmds.UpdateList)
                            {
                                if (up.tablename.ToUpper().Contains(querystr))
                                {
                                    ishad = true;
                                    msg += "更新表名、";
                                }
                            }
                        }
                        if (checkBox2.Checked)
                        {
                            foreach (AspfmDataSql sql in aspfmds.sqlList)
                            {
                                if (sql.SqlStr.ToUpper().Contains(querystr))
                                {
                                    ishad = true;
                                    msg += "查询语句、";
                                }
                            }
                        }
                        if (checkBox4.Checked)
                        {
                            foreach (AspfmExecSql exe in aspfmds.execList)
                            {
                                if (exe.SqlStr.ToUpper().Contains(querystr))
                                {
                                    ishad = true;
                                    msg += "执行SQL语句、";
                                }
                            }
                        }
                        if (checkBox5.Checked)
                        {
                            foreach (AspfmProcSql psql in aspfmds.procList)
                            {
                                if (psql.SqlStr.ToUpper().Contains(querystr))
                                {
                                    ishad = true;
                                    msg += "存储过程语句、";
                                }
                            }
                        }
                    }
                    if (checkBox7.Checked)
                    {
                        if (tempmd.html.Contains(textBox7.Text.Trim()))
                        {
                            ishad = true;
                            msg += "HtmlAndJS、";
                        }
                    }
                    if (ishad)
                    {
                        int rowindex=  dataGridView1.Rows.Add(tempmd.filename);
                        dataGridView1.Rows[rowindex].Cells[0].ToolTipText = msg;
                    }
                }
            }
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            DataGridView dgv = dataGridView1;
            if (tabControl1.SelectedIndex == 1)
            {
                dgv = dataGridView2;
            }
            List<int> rowindexlist = GetSelectRowIdList(dgv);
            if (rowindexlist.Count > 0)
            {
                foreach (int index in rowindexlist)
                {
                    string file = dgv.Rows[index].Cells[0].Value.ToString();
                    Aspfm.Control.Tool.Explorer.ExplorerFile(file);
                }
            }
        }
        private List<int> GetSelectRowIdList(DataGridView dgv)
        {
            List<int> rowindexlist = new List<int>();
            foreach (DataGridViewCell cell in dgv.SelectedCells)
            {
                if (!rowindexlist.Contains(cell.RowIndex))
                {
                    rowindexlist.Add(cell.RowIndex);
                }
            }
            return rowindexlist;
        }
        private void button4_Click(object sender, EventArgs e)
        {
            if (allAspxHtml == null)
            {
                allAspxHtml = new List<aspfmmodel>();
                serverpath = textBox1.Text.Trim().Trim('\\').Trim('/');

                var files = Directory.GetFiles(serverpath, "*.*", SearchOption.AllDirectories).
                    Where(s => s.ToLower().EndsWith(".aspx") || s.ToLower().EndsWith(".cshtml") || s.ToLower().EndsWith(".html"));
                foreach (string strfile in files)
                {
                    aspfmmodel tempaspfm = new aspfmmodel();
                    tempaspfm.filename = strfile;
                    tempaspfm.html = System.IO.File.ReadAllText(strfile,Encoding.UTF8).ToUpper();
                    allAspxHtml.Add(tempaspfm);
                }
            }
            dataGridView2.Rows.Clear();
            string querystr = textBox10.Text.ToUpper().Trim();
            if (!string.IsNullOrEmpty(querystr))
            {
                foreach (aspfmmodel tempmd in allAspxHtml)
                {
                    if (tempmd.html.Contains(querystr))
                    {
                        int rowindex = dataGridView2.Rows.Add(tempmd.filename);
                        //dataGridView1.Rows[rowindex].Cells[0].ToolTipText = msg;
                    }
                }
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            string oldstr = textBox13.Text.Trim();
            string newstr = textBox12.Text.Trim();

            if (!string.IsNullOrEmpty(oldstr))
            {
                bool isreplace = true;
                if (string.IsNullOrEmpty(newstr))
                {
                    if (MessageBox.Show("新内容为空，表示直接删除旧内容，是否确定？", "删除提示", MessageBoxButtons.YesNo) == DialogResult.No)
                    {
                        isreplace = false;
                    }
                }
                if (isreplace)
                {
                    serverpath = textBox11.Text.Trim().Trim('\\').Trim('/');
                    //string[] files = Directory.GetFiles(serverpath, "*.aspfm", SearchOption.AllDirectories);
                    string[] files = ConfigTool.GetFiles(serverpath, "*.aspfm", SearchOption.AllDirectories);
                    foreach (string strfile in files)
                    {
                        string temppath = System.IO.Path.GetTempPath() + Path.GetFileName(strfile);
                        if (string.IsNullOrEmpty(Aspfm.Dal.ZipHelper.unZipFile(strfile, Path.GetDirectoryName(temppath), Aspfm.Main.BaseAshx.Extension, true)))
                        {
                            FileStream fileStream = new FileStream(temppath, FileMode.Open, FileAccess.Read, FileShare.Read);
                            BinaryFormatter b = new BinaryFormatter();
                            AspfmAll AspfmAll = b.Deserialize(fileStream) as AspfmAll;
                            fileStream.Close();

                            if (AspfmAll != null && AspfmAll.DesignList != null)
                            {
                                foreach (AspfmEntity aspfmentity in AspfmAll.DesignList)
                                {
                                    ReplaceAspfm(aspfmentity, oldstr, newstr);
                                }
                            }
                            SaveAspfmFile(strfile, AspfmAll);
                        }
                    }
                    MessageBox.Show("升级完成");
                }
            }
        }
        private void ReplaceAspfm(AspfmEntity aspfmentity,string oldstr,string newstr)
        {
            aspfmentity.HtmlText.html = aspfmentity.HtmlText.html.Replace(oldstr, newstr);
            aspfmentity.HtmlText.js = aspfmentity.HtmlText.js.Replace(oldstr, newstr);

            if (aspfmentity.ChildList != null)
            {
                foreach (AspfmEntity centity in aspfmentity.ChildList)
                {
                    ReplaceAspfm(centity, oldstr, newstr);
                }
            }
        }
        internal void SaveAspfmFile(string filename, AspfmAll Aspfmall)
        {
            string temppath = System.IO.Path.GetTempPath() + Path.GetFileName(filename);
            //二进制序列化
            FileStream fileStream = new FileStream(temppath, FileMode.Create);
            BinaryFormatter b = new BinaryFormatter();
            b.Serialize(fileStream, Aspfmall);
            fileStream.Close();
            Aspfm.Dal.ZipHelper.ZipFile(temppath, filename, ".aspfm");
            File.Delete(temppath);
            DateTime Aspfmdate = DateTime.Now;
            System.IO.File.SetCreationTime(filename, Aspfmdate);
            System.IO.File.SetLastWriteTime(filename, Aspfmdate);
        }
    }
    public class aspfmmodel
    {
        public string filename = "";
        public List<AspfmDataSource> aspfmall = null;
        public string html = "";
    }
}
